package com.ccb.posrecord;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ccb.Constants;
import com.ccb.util.DateUtil;
import com.ccb.util.Record;
import com.ccb.util.RecordType;
import com.google.gson.JsonObject;

/**
 * 
 * @author flytoice
 *
 */
public class PosRecord extends PosCustomRecord {
	JSONObject json;
	Record rd;
//	JsonObject json;
	// 响应报文匹配提取
	private static final Pattern rspPattern = Pattern.compile("\\[([0-9]{14})\\]" + ".*txn_num\\[(.*)\\]" + ".*acct\\[(.*)\\]" + ".*amt\\[(.*)\\]" + ".*rsp_code\\[(.*)\\]" + ".*normal_key\\[(.*)\\]");

	// 请求报文normal_key部分
	private static final Pattern keyPattern = Pattern.compile(".*\\[([0-9]{14})\\]" +".*txn_num\\[(.*)\\] normal_key\\[([0-9]{1,}) *\\]");

	// //请求报文长度部分
	// private static final Pattern lenPattern = Pattern.compile(
	// "len=([0-9]{1,4})"
	// );

	private boolean lenFlag;
	private boolean entityFlag;
	private boolean keyFlag;

	private String lenPartVal;
	private String entityPartVal;

	private String value;

	public boolean isFlag1() {
		return lenFlag;
	}

	public boolean isFlag2() {
		return entityFlag;
	}

	public boolean isFlag3() {
		return keyFlag;
	}

	public String getValue() {
		return value;
	}

	public void setFlag1(boolean flag1) {
		this.lenFlag = flag1;
	}

	public void setFlag2(boolean flag2) {
		this.entityFlag = flag2;
	}

	public void setFlag3(boolean flag3) {
		this.keyFlag = flag3;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getValue1() {
		return lenPartVal;
	}

	public String getValue2() {
		return entityPartVal;
	}

	// public String getValue3() {
	// return keyPartVal;
	// }

	public void setValue1(String value1) {
		this.lenPartVal = value1;
	}

	public void setValue2(String value2) {
		this.entityPartVal = value2;
	}

	// public void setValue3(String value3) {
	// this.keyPartVal = value3;
	// }

	@Override
	public Text getValueForMapper() {

	//	return new Text(json.toString());
		return new Text(JSON.toJSONString(rd));

		// if (isRsp){
		// return new Text(groupKey+rsp);
		// } else {
		// return new Text(groupKey+lenPartVal+entityPartVal+keyPartVal);
		// }

	}

	@Override
	public boolean isYouNeedValue(LongWritable key, Text originalLog, PosCustomRecord o) {
		String dumy = originalLog.toString().trim();

		if ("".equals(dumy))
			return Boolean.FALSE;

		if (dumy.startsWith("-"))
			return Boolean.FALSE;

		if (dumy.contains("rsp_code")) {
		//	json = new JsonObject();
		//	json=new JSONObject();
			rd=new Record();
			if (rspParse(dumy, rd)) {
				return Boolean.TRUE;
			} else {
				return Boolean.FALSE;
			}
		}

		if (dumy.matches(".*\\[len=.*")) {
			initValue();
			lenPartVal = dumy;
			lenFlag = Boolean.TRUE;
		} else if (dumy.matches(".*[0-9]{4}:.*")) {
			if (!lenFlag) {
				initValue();
			} else {
				entityPartVal += dumy.substring(5, 54).trim().replace("  ", " ") + " ";
				entityFlag = Boolean.TRUE;
			}
		} else if (dumy.matches(".*normal_key\\[.*")) {
			if (!entityFlag) {
				initValue();
			} else {
				keyFlag = Boolean.TRUE;
				rd=new Record();
			//	json = new JsonObject();
				if (keyParse(dumy, rd)) {
					// 请求长度没有设置（后续处理暂不需要该字段）
				//	json.addProperty("message", entityPartVal.trim());
					rd.setOriginalData(entityPartVal.trim());
				} else {
					initValue();
				}
			}
		} else {
			throw new RuntimeException("未定义的数据格式，请检查数据文件");
		}

		// 返回最后一部分的标志（用最后一部分的标志表示该报文是否已经完整）
		return keyFlag;
	}

	private void initValue() {
		lenPartVal = "";
		lenFlag = Boolean.FALSE;

		entityPartVal = "";
		entityFlag = Boolean.FALSE;

		keyFlag = Boolean.FALSE;
	}

	/**
	 * 解析响应，并将响应字段保存在json中
	 * 
	 * @param message
	 * @param o
	 * @return
	 */
	//private boolean rspParse(String message, JsonObject o1) {
	private boolean rspParse(String message, Record rd) {
		Matcher m = rspPattern.matcher(message);
	//	JsonObject o=new JsonObject();
		JSONObject o=new JSONObject();
		boolean found = m.find();
		if (found){
//			o.addProperty("time", m.group(1).trim());
//			o.addProperty("txn", m.group(2).trim());
//			o.addProperty("acct", m.group(3).trim());
//			o.addProperty("amt", m.group(4).trim());
//			o.addProperty("rspCode", m.group(5).trim());
			
			o.put("time", m.group(1).trim());
			o.put("txn", m.group(2).trim());
			o.put("acct", m.group(3).trim());
			o.put("amt", m.group(4).trim());
			o.put("rspCode", m.group(5).trim());
		
			rd.setUid(m.group(6).trim());
		//	o1.put(Constants.MATCH_KEY, m.group(6).trim());
		//	o.addProperty(Constants.GROUP_KEY, m.group(2).trim());
		//	o.addProperty(Constants.MSG_FLAG_KEY,Constants.MSG_RSP_FLAG);
			rd.setServiceId( m.group(2).trim());
			rd.setResponseCode(m.group(5).trim());
			//o1.put("serviceId", m.group(2).trim());
			rd.setRecordType(RecordType.RESPONSE);
		//	o1.put("recordType",RecordType.RESPONSE.toString());
			rd.setOriginalData(message);
		//	o1.put("rsp_original_data",message);
			rd.setData(o);
		//	o1.add("rsp_json_data", o);
		} 
		
		return found;
	}

	/**
	 * 提取请求中的normal_key
	 * 
	 * @param message
	 * @param o
	 * @return
	 */
	//private boolean keyParse(String message, JsonObject o) {
	private boolean keyParse(String message,  Record rd) {
		Matcher m = keyPattern.matcher(message);
		boolean found = m.find();
		if (found){
			try {
				System.out.println("time1=["+ m.group(1).trim()+"]");
				String formatStr=DateUtil.date2Str("yyyy-MM-dd HH:mm:ss.SSS", DateUtil.str2Date("yyyyMMddHHmmss", m.group(1).trim()));
				System.out.println("formatStr=["+ formatStr+"]");
				Timestamp time=Timestamp.valueOf(formatStr);
				System.out.println("time2=["+ time+"]");
				rd.setTime(time);
				
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
		//	Timestamp time=Timestamp.valueOf(m.group(2).trim());
			//rd.setTime(time);
			rd.setUid(m.group(3).trim());
			//o.addProperty(Constants.MATCH_KEY, m.group(2).trim());
			rd.setServiceId(m.group(2).trim());
			//o.addProperty("serviceId", m.group(1).trim());
			rd.setRecordType(RecordType.REQUEST);
		//	rd.setTime(time);
		//	o.addProperty("recordType","REQUEST");
		//	o.addProperty("logType","pos");
		//	o.addProperty("changeFlag",false);
		//	o.addProperty("req_json_data","");
		//	o.addProperty("rsp_json_data","");
		}
		return found;
	}

	// /**
	// * 提取请求中的报文长度
	// * @param message
	// * @param o
	// * @return
	// */
	// private boolean lenParse(String message,JsonObject o){
	// Matcher m = lenPattern.matcher(message);
	// boolean found = m.find();
	// if (found){
	// o.addProperty("len", m.group(1).trim());
	// }
	// return found;
	// }

	public static void main(String[] args) {
		PosRecord r = new PosRecord();
		JsonObject j = new JsonObject();
	//	System.out.println(r.rspParse("[20161002001526][Normal.c][264] txn_num[8031] acct[1000] amt[2000] rsp_code[00] normal_key[105610244444339             ]", j));

		System.out.println(j.toString());

	}
}
